/*
 * ResultSetTableModel.java
 *
 * Created on January 18, 2006, 12:07 PM
 *
 */

package jerbo.util;

import java.sql.*;

import java.util.ResourceBundle;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Luigi Paioro
 */
public class ResultSetTableModel extends AbstractTableModel {
    
    protected ResultSet rs ;
    protected ResultSetMetaData rsmd;
    protected ResourceBundle bundle;
    
    /** Creates a new instance of ResultSetTableModel
     * @param rs
     * @param bundle 
     */
    public ResultSetTableModel(ResultSet rs, ResourceBundle bundle) {
        this.rs = rs;
        this.bundle = bundle;
        try {
            this.rsmd = rs.getMetaData();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        }
    }
    
    public Object getValueAt(int row, int col) {
        try {
            rs.absolute(row + 1);
            return rs.getObject(col + 1);
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            return null;
        }
    }

    public int getRowCount() {
        try {
            rs.last();
            return rs.getRow();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            return 0;
        }
    }

    public int getColumnCount() {
        try {
            return rsmd.getColumnCount();
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            return 0;
        }
    }
    
    @Override
    public String getColumnName(int col) {
        try {
            return bundle.getString("table.header."+rsmd.getColumnName(col + 1));
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            return "Column " + String.valueOf(col + 1);
        }
    }
    
    @Override
    public Class getColumnClass(int col) {
        try {
            return rs.getObject(col + 1).getClass();
        } catch (Exception ex) {
            //ex.printStackTrace();
            return String.class;
        }        
    }
}
